//用户管理的路由
//1.引入express框架
const express = require('express');
const db = require('../modules/DBhelper');
const moment = require('moment');

//创建路由
let router = express.Router();

//登录
router.post('/login', async function (request, response, next) {
    //获取前端数据
    let userObj = request.body;
    //获取数据库
    let sql = 'SELECT * FROM `user_info` WHERE `u_username`=? AND `u_password`=? ;';
    let param = [
        userObj.username,
        userObj.password
    ];
    let result = await db.exec(sql, param);
    if (result && result.length >= 1) {
        delete (result[0].u_password)
        response.json({
            msg: '登录成功',
            status: 200,
            data: result[0]
        });
    } else {
        response.json({
            msg: '登录失败',
            status: -200,
        })
    }
})

//检测用户名注册是否重复
router.get('/checkName', async function (request, response, next) {
    let sql = 'SELECT * FROM `user_info` WHERE `u_username`=? ;';
    try {
        let result = await db.exec(sql, [request.query.username]);
        let isExist = result && result.length >= 1;
        response.end((!isExist).toString());
    } catch (e) {
        response.end("false");
    }
})

//注册
router.post('/reg', async function (request, response, next) {
    //获取前端数据
    let userObj = request.body;
    //传入数据库
    let sql = 'INSERT INTO `user_info`(`u_username`,`u_password`,`u_nickname`,`u_createtime`) VALUE(?,?,?,?) ;';
    let param = [
        userObj.username,
        userObj.password,
        userObj.nickname,
        moment().format('YYYY-MM-DD HH:mm:ss')
    ];
    try {
        let result = await db.exec(sql, param);
        let isReg = result && result.affectedRows >= 1;
        response.json({
            msg: isReg ? '注册成功' : '注册失败',
            status: isReg ? 200 : -200
        })
    } catch (e) {
        response.json({
            msg: '意外错误',
            status: -200,
            e
        })
    }
});

//暴露
module.exports = {router};
